package com.hns.can.upgrade.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hns.can.common.domain.GridPage;
import com.hns.can.common.domain.ReturnResult;
import com.hns.can.common.web.BaseController;
import com.hns.can.upgrade.entity.UpgPhoneParam;
import com.hns.can.upgrade.entity.UpgPhoneVrsn;
import com.hns.can.upgrade.service.UpgPhoneVrsnService;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.util.BeanUtilsByOverwriteSpring;
import com.hns.tool.pub.FTPUtils;
import com.hns.tool.pub.SAXUtil;
import com.hns.tool.pub.UtilConfig;
import com.hns.tool.pub.UtilString;

/**
 * @ClassName: UpgPhoneVrsnController
 * @Description: 手机升级版本controller
 * @author zhangl
 * @email victor_007@126.com
 * @date 2016年11月15日 下午4:16:58
 */
@Controller
@RequestMapping("upgPhone")
public class UpgPhoneVrsnController extends BaseController {
    @Autowired
    private UpgPhoneVrsnService upgPhoneVrsnService;

    /**
     * @Title: getUpgPhoneVrsnPage
     * @Description: 手机版本分页
     * @param request
     * @return Object
     */
    @RequestMapping("getUpgPhoneVrsnPage")
    @ResponseBody
    public Object getUpgPhoneVrsnPage(HttpServletRequest request) {
        Map<String, Object> params = getParameter_prefix();
        Pagination page = upgPhoneVrsnService.getUpgPhoneVrsnPage(params);
        GridPage grid = new GridPage(page);
        return new ReturnResult(grid);
    }

    /**
     * @Title: getUpgPhoneParamList
     * @Description: 手机参数列表
     * @return Object
     */
    @RequestMapping("getUpgPhoneParamList")
    @ResponseBody
    public Object getUpgPhoneParamList() {
        Map<String, Object> params = getParameter_prefix();
        List data = upgPhoneVrsnService.getUpgPhoneParamList(params);
        // Object object = JSON.parse(JSON.toJSONString(data,SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat));
        return new ReturnResult(data);
        // Pagination page = upgPhoneVrsnService.getUpgPhoneParamPage(params);
        // GridPage grid = new GridPage(page);
        // return new ReturnResult(grid);
    }

    /**
     * @Title: saveFile
     * @Description: 保存文件
     * @param type
     * @param uploadFile
     * @return String
     */
    public String saveFile(String type, MultipartFile uploadFile) {
        StringBuffer fullPath = new StringBuffer(100);
        String basePath = "";
        String configPath = "";
        String packagePath = "";
        String oldFileName = "";
        try {
            if (uploadFile != null) {
                basePath = UtilConfig.getString("ftp_update_center_phone");
                if (type.equalsIgnoreCase("TEL00001")) {
                    configPath = "ios/config/";
                    packagePath = "ios/package/";
                } else {
                    configPath = "android/config/";
                    packagePath = "android/package/";
                }
                oldFileName = uploadFile.getOriginalFilename();
                FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), basePath + packagePath);
                FTPUtils.ftpUpload(uploadFile.getInputStream(), basePath + packagePath, new String(oldFileName.getBytes(), "ISO-8859-1"));
                fullPath.append(basePath).append(packagePath).append(oldFileName);

                if (type.equalsIgnoreCase("TEL00001")) {
                    // 修改plist文件
                    File plistFile = SAXUtil.writePlist("string", 1, UtilConfig.getString("file_url") + configPath + new String(oldFileName.getBytes(), "ISO-8859-1"), false);
                    FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), basePath + configPath);
                    FTPUtils.ftpUpload(new FileInputStream(plistFile), basePath + configPath, plistFile.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fullPath.toString();
    }

    /**
     * @Title: editUpgPhoneVrsn
     * @Description: 手机版本编辑
     * @param uploadFile
     * @param entity
     * @return Object
     */
    @RequestMapping("editUpgPhoneVrsn")
    @ResponseBody
    public Object editUpgPhoneVrsn(MultipartFile uploadFile, UpgPhoneVrsn entity) {
        String fullPath = this.saveFile(entity.getVrsnType(), uploadFile);
        entity.setUpgFile(fullPath);
        if (entity.getId() != null && !entity.getId().equals("")) {
            UpgPhoneVrsn getUpgPhoneVrsn = upgPhoneVrsnService.getUpgPhoneVrsn(entity.getId());
            BeanUtilsByOverwriteSpring.copyProperties(entity, getUpgPhoneVrsn);

            upgPhoneVrsnService.updUpgPhoneVrsn(getUpgPhoneVrsn);
        } else {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("type", entity.getVrsnType());
            UpgPhoneParam upgPhoneParam = upgPhoneVrsnService.getUpgPhoneParam(params);
            entity.setParamId(upgPhoneParam.getId());
            entity.setCrtTime(new Date());
            entity.setId(UtilString.getUUID());
            upgPhoneVrsnService.addUpgPhoneVrsn(entity);
        }
        return this.getReturnResult();
    }

    /**
     * @Title: editUpgPhoneParam
     * @Description: 手机参数编辑
     * @param uploadFile
     * @param uploadLogo
     * @param uploadLogo2
     * @param entity
     * @return Object
     */
    @RequestMapping("editUpgPhoneParam")
    @ResponseBody
    public Object editUpgPhoneParam(MultipartFile uploadFile, MultipartFile uploadLogo, MultipartFile uploadLogo2, UpgPhoneParam entity) {
        // String savePath = request.getSession().getServletContext().getRealPath("/upgPhone");
        // String logo = "";
        // String logo2 = "";
        // String fileName = "";
        // try{
        // if(uploadFile != null){
        // fileName = uploadFile.getOriginalFilename();
        // if(fileName.trim() !=""){
        // File savedFile = new File(savePath, fileName);
        // uploadFile.transferTo(savedFile);
        // }
        // }
        // if(uploadLogo != null){
        // logo = uploadFile.getOriginalFilename();
        // if(logo.trim() !=""){
        // File savedFile = new File(savePath, logo);
        // uploadLogo.transferTo(savedFile);
        // }
        // }
        // if(uploadFile != null){
        // logo2 = uploadFile.getOriginalFilename();
        // if(logo2.trim() !=""){
        // File savedFile = new File(savePath, logo2);
        // uploadLogo2.transferTo(savedFile);
        // }
        // }
        // }catch (Exception e) {
        // e.printStackTrace();
        // }
        //
        // entity.setLogo("upgPhone/"+logo);
        // entity.setLogo2("upgPhone/"+logo2);
        // entity.setFilePath("upgPhone/"+fileName);
        if (entity.getId() != null && !entity.getId().equals("")) {
            UpgPhoneParam getUpgPhoneParam = upgPhoneVrsnService.getUpgPhoneParam(entity.getId());
            BeanUtilsByOverwriteSpring.copyProperties(entity, getUpgPhoneParam);

            upgPhoneVrsnService.updUpgPhoneParam(getUpgPhoneParam);
        }
        return this.getReturnResult();
    }

    /**
     * @Title: deleteUpgPhoneVrsn
     * @Description: 手机参数删除
     * @param vrsnIds
     * @return Object
     */
    @RequestMapping("deleteUpgPhoneVrsn")
    @ResponseBody
    public Object deleteUpgPhoneVrsn(@RequestParam("vrsnIds") String[] vrsnIds) {
        upgPhoneVrsnService.deleteUpgPhoneVrsn(vrsnIds);
        return this.getReturnResult();
    }

    /**
     * @Title: getUpgPhoneVrsn
     * @Description: 单个手机版本信息
     * @param vrsnId
     * @return Object
     */
    @RequestMapping("getUpgPhoneVrsn")
    @ResponseBody
    public Object getUpgPhoneVrsn(@RequestParam("vrsnId") String vrsnId) {
        UpgPhoneVrsn upgPhoneVrsn = upgPhoneVrsnService.getUpgPhoneVrsn(vrsnId);
        return this.getReturnResult(upgPhoneVrsn);
    }

    /**
     * @Title: getUpgPhoneParam
     * @Description: 单个手机参数信息
     * @param vrsnId
     * @return Object
     */
    @RequestMapping("getUpgPhoneParam")
    @ResponseBody
    public Object getUpgPhoneParam(@RequestParam("paramId") String vrsnId) {
        UpgPhoneParam upgPhoneParam = upgPhoneVrsnService.getUpgPhoneParam(vrsnId);
        return this.getReturnResult(upgPhoneParam);
    }

    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response,@RequestParam("vrsnId") String vrsnId) throws Exception {
        UpgPhoneVrsn upgPhoneVrsn = upgPhoneVrsnService.getUpgPhoneVrsn(vrsnId);
        String remoteFile = "";
        FTPClient ftpClient = FTPUtils.getInstance().getClient();
        OutputStream out = null;
        if (upgPhoneVrsn != null) {
            remoteFile = upgPhoneVrsn.getUpgFile();
            try {
                String fileName = remoteFile.substring(remoteFile.lastIndexOf("/") + 1);
                InputStream inputStream = ftpClient.retrieveFileStream(new String(remoteFile.getBytes(), "ISO-8859-1"));

                if (inputStream != null) {
                    out = response.getOutputStream();
                    response.reset();
                    //response.setContentType("application/octet-stream; charset=utf-8");
                    response.setContentType("application/x-download; charset=utf-8");
                    response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    inputStream.close();
                    out.flush();
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }

    // /**
    // *
    // * @Title: getFileUrl
    // * @Description: 文件url
    // * @return
    // * Object
    // */
    // @RequestMapping("getFileUrl")
    // @ResponseBody
    // public Object getFileUrl(){
    // return this.getReturnResult(UtilConfig.getString("file_url"));
    // }
}
